package icom.acm.servlet.listener;

import icom.acm.bean.T_USER;
import icom.acm.manager.T_UserOnlineMgr;
import icom.acm.manager.T_UserSetMgr;
import icom.acm.util.StaticData;
import icom.acm.util.mongo.MongoDB;
import icom.acm.util.redis.RedisDB;
import icom.acm.util.spring.SpringFactory;

import java.util.HashMap;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.directwebremoting.ScriptSession;


public class MyListener implements HttpSessionListener,
		HttpSessionAttributeListener, ServletContextListener {

	@Override
	public void sessionCreated(final HttpSessionEvent arg) {
		System.out.println("创建了一个session");

	}

	@Override
	public void sessionDestroyed(final HttpSessionEvent arg0) {	
		System.out.println("注销了一个session");
	}

	@Override
	public void attributeAdded(final HttpSessionBindingEvent arg) {
		System.out.println("添加了一个session属性:" + arg.getName());
	}

	@Override
	public void attributeRemoved(final HttpSessionBindingEvent arg) {
		String name = arg.getName();
		if (name.equals("user")){
			T_UserOnlineMgr uomgr = new T_UserOnlineMgr(); 
			T_USER u = (T_USER)arg.getValue();
			uomgr.deleteById(u.getU_ID());			
		}
		System.out.println("删除了一个session属性:" + arg.getName());

	}

	@Override
	public void attributeReplaced(final HttpSessionBindingEvent arg0) {
		System.out.println("重设了一个session属性");

	}

	@Override
	public void contextDestroyed(final ServletContextEvent arg) {
		System.out.println("注销了一个application");
		StaticData.application = null;
	}

	@Override
	public void contextInitialized(final ServletContextEvent arg) {
		System.out.println("创建了一个application");
		StaticData.application = arg.getServletContext();
		StaticData.WEB_PATH = arg.getServletContext().getRealPath("/");
		StaticData.WEBINF_PATH = StaticData.WEB_PATH
				+ "WEB-INF/";
		System.out.println(StaticData.WEBINF_PATH);
		StaticData.WEBU_PATH = StaticData.WEB_PATH
		+ "u/";
		
		if (StaticData.USERSETLIST == null){	//  加载数据
			T_UserSetMgr usm = new T_UserSetMgr();
			StaticData.USERSETLIST = usm.toTreeList();
		}
		T_UserOnlineMgr uomgr = new T_UserOnlineMgr();
		uomgr.deleteAll();		// 还原用户在线
		
System.out.println("创建缓存区...");

System.out.println("配置mongoDB");		
		
		
System.out.println("初始化mongodb数据库...");
		MongoDB.newInstance();
System.out.println("初始化mongodb数据库完成!");		
System.out.println("初始化redis数据库...");
		RedisDB.newInstance();
		
System.out.println("初始化redis数据库完成!");
		StaticData.SESSIONID_SCRIPTSESSION_MAP = new HashMap<String, ScriptSession>();
System.out.println("完成缓存区");
	}
}
